package com.jiayi.common.developutil;

import com.jiayi.common.utils.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * 转换工具类
 *
 * @author liuzekun
 * Create at 2024/5/31
 */
public class ConvertUtils {

    public ConvertUtils() {
    }

    /**
     * 字符串解析
     *
     * @param str      字符串
     * @param function 方法
     * @param split    解析符
     * @param <R>      出参模版
     * @return 目标类型
     */
    public static <R> List<R> split(String str, Function<String, R> function, String split) {
        if (StringUtils.isEmpty(str)) {
            return Collections.emptyList();
        }
        return Arrays
                .stream(str.split(split))
                .map(function)
                .collect(Collectors.toList());
    }

    public static <T, R> Collection<R> convert(Collection<T> items, Function<T, R> function) {
        return CollectionUtils.isEmpty(items) ? Collections.emptyList() : (List) items.stream().map(function).collect(Collectors.toList());
    }

    public static <T, R> List<R> convert(List<T> items, Function<T, R> function) {
        return CollectionUtils.isEmpty(items) ? Collections.emptyList() : (List) items.stream().map(function).collect(Collectors.toList());
    }

    public static <T, R> List<R> convertNotNull(List<T> items, Function<T, R> function) {
        return CollectionUtils.isEmpty(items) ? Collections.emptyList() : (List) items.stream().map(function).filter(e -> e != null).collect(Collectors.toList());
    }

    public static <T, R> List<R> filter(List<T> items, Predicate<T> function) {
        return CollectionUtils.isEmpty(items) ? Collections.emptyList() : (List) items.stream().filter(function).collect(Collectors.toList());
    }

    public static <T, R> List<R> convert(T[] items, Function<T, R> function) {
        return items != null && items.length != 0 ? (List) Arrays.stream(items).map(function).collect(Collectors.toList()) : Collections.emptyList();
    }

    public static <T, R> R convertSingle(T item, Function<T, R> function) {
        return item == null ? null : function.apply(item);
    }

    public static <T, R> List<R> parallelConvert(List<T> items, Function<T, R> function) {
        return CollectionUtils.isEmpty(items) ? Collections.emptyList() : (List) items.parallelStream().map(function).collect(Collectors.toList());
    }

    public static <R> List<R> convert(String str, Function<String, R> function, String split) {
        return StringUtils.isEmpty(str) ? Collections.emptyList() : (List) Arrays.stream(str.split(split)).map(function).collect(Collectors.toList());
    }
}
